package top.purity.server.tenant.feign.output.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import top.purity.framework.common.exception.ServiceException;
import top.purity.server.tenant.domain.cache.TenantUserCache;
import top.purity.server.tenant.domain.TenantMenu;
import top.purity.server.tenant.domain.TenantUser;
import top.purity.server.tenant.domain.repository.TenantMenuRepository;
import top.purity.server.tenant.feign.output.TenantFeign;
import top.purity.server.tenant.feign.output.dto.PermissionDTO;
import top.purity.server.tenant.feign.output.dto.TenantInfoDTO;
import top.purity.server.tenant.service.convert.TenantMenuConvert;
import top.purity.server.tenant.service.convert.TenantUserConvert;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @version 1.0
 * @Author Lmh
 * @Description
 * @CreateTime 2023-09-24 20:31
 */

@RestController
@RequiredArgsConstructor
@Slf4j
public class TenantFeignImpl implements TenantFeign {

    private final TenantMenuRepository tenantMenuRepository;

    private final TenantUserCache tenantUserCache;

    @Override
    public TenantInfoDTO getByCode(String code) throws ServiceException {
        TenantUser tenantUser = tenantUserCache.getTenantInfoByCode(code);

        if (ObjUtil.isEmpty(tenantUser)) {
            throw new ServiceException("不存在的租户");
        }

        return TenantUserConvert.INSTANCE.convertToTenantInfoDto(tenantUser);
    }

    @Override
    public List<PermissionDTO> getMenuListByIds(Set<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }

        Collection<TenantMenu> tenantMenus = tenantMenuRepository.getTenantMenuDOByIdIn(ids);
        return TenantMenuConvert.INSTANCE.convertToPermissionDtoList(tenantMenus);
    }

    @Override
    public PermissionDTO getMenuByPath(String path) {
        TenantMenu tenantMenu = tenantMenuRepository.getTenantMenuDOByMenuUriLike(path);
        return TenantMenuConvert.INSTANCE.convertToPermissionDto(tenantMenu);
    }
}
